package com.qire.manhua.model.viewModel.impl;

import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.view.View;

import com.qire.common.SummerApp;
import com.qire.common.basic.ObjectUtil;
import com.qire.common.collect.ListUtil;
import com.qire.common.support.base.BaseViewModel;
import com.qire.common.support.base.IViewModel;
import com.qire.common.widget.adapter.auto.AutoVariable;
import com.qire.common.widget.adapter.auto.SummerRecyclerBindAdapter;
import com.qire.common.widget.adapter.auto.annotation.AdapterEntityBind;
import com.qire.manhua.BR;
import com.qire.manhua.R;
import com.qire.manhua.activity.ComicDownloadProgressActivity;
import com.qire.manhua.controller.ComicDownloadProgressController;
import com.qire.manhua.dal.service.ComicDownloadProgressService;
import com.qire.manhua.databinding.LayoutComicDownloadProgressItemBinding;
import com.qire.manhua.model.entity.ComicBookEntity;
import com.qire.manhua.model.po.LocalComicChapter;
import com.qire.manhua.service.ComicDownloadService;
import com.qire.manhua.service.ComicDownloadService.ComicDownloadBinder;
import com.qire.manhua.service.ComicDownloadService.ProgressObserver;

import java.util.ArrayList;
import java.util.Iterator;

import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import androidx.lifecycle.MutableLiveData;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import androidx.recyclerview.widget.RecyclerView.LayoutManager;

public class ComicDownloadProgressViewModel extends BaseViewModel implements IViewModel, ProgressObserver {

    private ComicDownloadProgressService progressService = new ComicDownloadProgressService(this);

    private final ArrayList<DownloadProgressItemViewModel> progressList = new ArrayList();
    private final SummerRecyclerBindAdapter progressAdapter = new SummerRecyclerBindAdapter(progressList);
    private final LinearLayoutManager progressLayoutManager= new LinearLayoutManager(null);

    private ComicDownloadProgressActivity activity;

    private ComicBookEntity comicBookEntity;

    private boolean isEditMode  = false;
    private boolean isDescMode  = false;

    private final ArrayList<DownloadProgressItemViewModel> deleteList = new ArrayList<>();

    @Override
    public int getVariableId() {
        return BR.comicDownloadProgressViewModel;
    }

    @Override
    public void update(LocalComicChapter comicChapter) {
        Iterator<DownloadProgressItemViewModel> iterator = progressList.iterator();
        while (iterator.hasNext()) {
            DownloadProgressItemViewModel itemViewModel = iterator.next();
            LocalComicChapter itemChapter = itemViewModel.chapter;
            if(itemChapter.getId() == comicChapter.getId()) {
                itemChapter.setDownloadCount(comicChapter.getDownloadCount());
                itemChapter.setDownloadState(comicChapter.getDownloadState());
                if(ObjectUtil.nonNull(activity)) {
                    activity.runOnUiThread(() -> {
                        itemViewModel.notifyChange();
                        refreshAllBatchOperationBtnUI();
                    });
                }
            }
        }
    }

    private final ServiceConnection serviceConnection = new ServiceConnection() {
        ComicDownloadBinder comicDownloadBinder;
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            comicDownloadBinder = (ComicDownloadBinder) service;
            comicDownloadBinder.addObserver(ComicDownloadProgressViewModel.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            if(ObjectUtil.nonNull(comicDownloadBinder)) {
                comicDownloadBinder.removeObserver(ComicDownloadProgressViewModel.this);
            }
        }
    };

    //region    #附加管理 begin
    /**
     * 附加属性绑定
     * @param controller 事件控制器
     */
    public void onAddition(ComicDownloadProgressActivity activity, ComicDownloadProgressController controller) {
        this.activity = activity;
//        this.controller = controller;
        this.progressAdapter.setEventProcess(controller);
        refreshUI();
        bindDownloadService();
    }

    /**
     * 清理函数，在Activity退出时，ViewModel生命周期到期会被回收，调用该事件，
     * 页面由于切换、横竖屏转换、内存回收等情况并不会影响到ViewModel的生命周期。
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        unBindDownloadService();
        this.activity = null;
//        this.controller = null;
        this.progressService = null;
        this.progressAdapter.setEventProcess(null);
    }
    //endregion #附加管理 end

    //region #业务数据

    public void loadComicBookEntity(ComicBookEntity comicBookEntity) {
        this.comicBookEntity = comicBookEntity;
        progressService.loadComicChapter();
        setTitle(comicBookEntity.bookName);
    }

    public void progressListClear() {
        progressList.clear();
    }

    public void addProgressItem(LocalComicChapter comicChapter) {
        progressList.add(new DownloadProgressItemViewModel(comicChapter));
    }

    public void refreshAdapter() {
        progressAdapter.notifyDataSetChanged();
    }

    public void bindDownloadService() {
        ComicDownloadService.bindService(activity, serviceConnection);
    }

    public void unBindDownloadService() {
        ComicDownloadService.unBindService(activity, serviceConnection);
    }

    public void updateDownloadService(int downloadActionFlags, int... chapterId) {
        ComicDownloadService.startService(SummerApp.summerApp(), downloadActionFlags, chapterId);
    }

    public ComicBookEntity comicBookEntity() {
        return comicBookEntity;
    }

    public int comicBookId() {
        return comicBookEntity.id;
    }

    public boolean isEditMode() {
        return isEditMode;
    }

    /**
     * 有正在下载的任务
     * @return true 有，false 无
     */
    public boolean haveDownloading() {
        if(progressList.isEmpty()) {
            return false;
        }
        for(DownloadProgressItemViewModel itemViewModel : progressList) {
            if(itemViewModel.isDownloading()) {
                return true;
            }
        }
        return false;
    }

    public void batchToggleDownloadStatus() {
        if(ListUtil.notEmpty(progressList)) {
            int size = progressList.size();
            boolean isDownloading = haveDownloading();
            int[] chapterIds = new int[size];
            for(int index = 0; index < size; index++) {
                chapterIds[index] = progressList.get(index).chapter.getId();
            }
            int downloadActionFlags = isDownloading ? ComicDownloadService.ACTION_PAUSE : ComicDownloadService.ACTION_START ;
            updateDownloadService(downloadActionFlags, chapterIds);
        }
    }

    public boolean noSelect() {
        return ListUtil.isEmpty(deleteList);
    }

    /**
     * 批量删除下载记录：<br />
     * 1.遍历所有选中章节，暂停正在下载的任务；<br />
     * 2.遍历删除所有选择章节数据库记录；<br />
     * 3.遍历删除所有选择的漫画章节下载目录文件
     */
    public void batchDelDownloadRecord() {

        int deleteListSize = deleteList.size();

        int[] delChapterIds = new int[deleteListSize];
        LocalComicChapter[] comicChapters = new LocalComicChapter[deleteListSize];

        for(int index = (deleteListSize - 1); index >= 0; index--) {
            DownloadProgressItemViewModel itemViewModel = deleteList.get(index);

            comicChapters[index] = itemViewModel.chapter;
            delChapterIds[index] = itemViewModel.chapter.getId();

            progressList.remove(itemViewModel);
            deleteList.remove(itemViewModel);
        }

        // 停止下载服务
        updateDownloadService(ComicDownloadService.ACTION_PAUSE, delChapterIds);
        // 删除记录，数据库及文件目录
        progressService.batchDeleteDownloadRecord(comicChapters);
        // 刷新页面UI
        refreshUI();
    }

    //endregion #业务数据 end

    //region #UI操作

    public void setTitle(CharSequence title) {
        set("title", title);
    }

    public void refreshUI() {
        refreshTipsUi();
        refreshAllBatchOperationBtnUI();
        refreshBottomEditMenuUI();
        progressAdapter.notifyDataSetChanged();
    }

    public void refreshTipsUi() {
        set("countTipsText", "共" + progressList.size() + "话");
    }

    public void refreshAllBatchOperationBtnUI() {
        boolean haveDownloading = haveDownloading();

        set("allBatchOperationBtnIconRes", haveDownloading ?
                R.drawable.app_comic_download_progress_icon_pause :
                R.drawable.app_comic_download_progress_icon_continue);

        set("allBatchOperationBtnText", haveDownloading ? "全部暂停" : "全部开始");
    }

    public void refreshBottomEditMenuUI() {
        int selectCount = deleteList.size();

        boolean isAllSelect = ListUtil.notEmpty(progressList) && selectCount >= progressList.size();
        set("allSelectIconState", isAllSelect);
        set("allSelectTextColor", isAllSelect ? "#ffff950b" : "#ff5c5c5c");

        boolean haveSelect = ListUtil.notEmpty(deleteList);
        String deleteSelectBtnText = "删除选中" + (haveSelect ? "(" + selectCount + ")" : "");
        set("deleteSelectBtnIconState", haveSelect);
        set("deleteSelectBtnText", deleteSelectBtnText);
        set("deleteSelectBtnTextColor", haveSelect ? "#ffff950b" : "#ff5c5c5c");
    }

    public void toggleEditMode() {
        isEditMode = !isEditMode;
        set("bottomMenuPageNo", isEditMode ? 1 : 0);
        refreshAdapter();
    }

    public void toggleSortMode() {
        isDescMode = !isDescMode;
        refreshUI();
        progressLayoutManager.setStackFromEnd(isDescMode);
        progressLayoutManager.setReverseLayout(isDescMode);
    }

    public void toggleAllSelect() {
        boolean isAllSelect = deleteList.size() >= progressList.size();
        for(DownloadProgressItemViewModel itemViewModel : progressList){
            if(itemViewModel.isSelect == isAllSelect) {
                itemViewModel.toggleSelect();
            }
        }
    }

    //endregion #UI操作 end

    //region #UI绑定

    public MutableLiveData<CharSequence> getTitle() {
        return get("title");
    }

    public MutableLiveData<CharSequence> getCountTipsText() {
        return get("countTipsText");
    }

    public MutableLiveData<Integer> getBottomMenuPageNo() {
        return get("bottomMenuPageNo");
    }

    public MutableLiveData<Integer> getAllBatchOperationBtnIconRes() {
        return get("allBatchOperationBtnIconRes");
    }
    public MutableLiveData<CharSequence> getAllBatchOperationBtnText() {
        return get("allBatchOperationBtnText");
    }

    public MutableLiveData<Boolean> getAllSelectIconState() {
        return get("allSelectIconState");
    }
    public MutableLiveData<String> getAllSelectTextColor() {
        return get("allSelectTextColor");
    }

    public MutableLiveData<Boolean> getDeleteSelectBtnIconState() {
        return get("deleteSelectBtnIconState");
    }
    public MutableLiveData<CharSequence> getDeleteSelectBtnText() {
        return get("deleteSelectBtnText");
    }
    public MutableLiveData<String> getDeleteSelectBtnTextColor() {
        return get("deleteSelectBtnTextColor");
    }

    public Adapter getProgressAdapter() {
        return progressAdapter;
    }

    public LayoutManager getProgressLayoutManager() {
        return progressLayoutManager;
    }

    //endregion #UI绑定 end

    @AdapterEntityBind(viewRid = R.layout.layout_comic_download_progress_item)
    public class DownloadProgressItemViewModel extends BaseObservable implements AutoVariable<LayoutComicDownloadProgressItemBinding> {

        public final LocalComicChapter chapter;

        private boolean isSelect = false;

        public DownloadProgressItemViewModel(LocalComicChapter chapter) {
            this.chapter = chapter;
        }

        @Override
        public void bindVariable(LayoutComicDownloadProgressItemBinding viewBind) {
            viewBind.setDownloadProgressItemViewModel(this);
        }

        public boolean isDownloadComplete(){
            return chapter.isDownloadComplete();
        }

        public boolean isDownloading() {
            return chapter.isDownloading();
        }

        public void toggleSelect() {
            isSelect = !isSelect;
            if(isSelect) {
                deleteList.add(this);
            } else {
                deleteList.remove(this);
            }
            notifyChange();
            refreshBottomEditMenuUI();
        }

        /**
         * 切换下载状态，如果正在下载，则切换到暂停，如果暂停中，则切换下载
         */
        public void toggleDownloadStatus() {
            int downloadActionFlags = isDownloading() ? ComicDownloadService.ACTION_PAUSE : ComicDownloadService.ACTION_START ;
            updateDownloadService(downloadActionFlags, chapter.getId());
        }

        @Bindable
        public int getSelectButtonVisible(){
            return isEditMode ? View.VISIBLE : View.GONE;
        }
        @Bindable
        public int getSelectButtonIconRes(){
            return isSelect ? R.drawable.app_comic_download_progress_icon_radio_b : R.drawable.app_comic_download_progress_icon_radio_a;
        }

        @Bindable
        public CharSequence getTileText(){
            return chapter.getChapterName();
        }

        @Bindable
        public int getProgressMax(){
            return chapter.getContentList().size();
        }
        @Bindable
        public int getProgressVale(){
            return chapter.getDownloadCount();
        }
        @Bindable
        public CharSequence getProgressText(){
            return "(" + getProgressVale() + "/" + chapter.getContentList().size() + ")";
        }

        @Bindable
        public CharSequence getDownloadStatusTipsText() {
            return chapter.currDownloadStateName();
        }

        @Bindable
        public int getControllerButtonVisible() {
            return isEditMode ? View.GONE : View.VISIBLE;
        }
        @Bindable
        public int getControllerButtonIconRes() {
            if(chapter.isDownloadComplete()) {
                return R.drawable.app_comic_download_progress_icon_item_read;
            } else if(chapter.isDownloading()) {
                return R.drawable.app_comic_download_progress_icon_item_pause;
            } else {
                return R.drawable.app_comic_download_progress_icon_item_continue;
            }
        }

    }

}
